package com.btpj.jetpack.http.api

import com.btpj.jetpack.http.exception.DealException
import com.btpj.jetpack.http.exception.ResultException
import com.btpj.jetpack.entity.ApiResponse
import com.btpj.jetpack.entity.ApiResult
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope

/**
 * 数据请求仓库基类
 *
 * @author LTP 2020/7/8
 */
open class BaseRepository {

    suspend fun <T : Any> callRequest(call: suspend () -> ApiResult<T>): ApiResult<T> {
        return try {
            call()
        } catch (e: Exception) {
            // 异常统一处理
            ApiResult.Error(DealException.handleException(e))
        }
    }

    /**
     * 请求执行
     */
    suspend fun <T : Any> handleResponse(
        response: ApiResponse<T>,
        successBlock: (suspend CoroutineScope.() -> Unit)? = null,
        errorBlock: (suspend CoroutineScope.() -> Unit)? = null
    ): ApiResult<T> {
        return coroutineScope {
            if (response.errorCode == -1) {
                errorBlock?.let { it() }
                ApiResult.Error(
                    ResultException(response.errorCode.toString(), response.errorMsg)
                )
            } else {
                successBlock?.let { it() }
                ApiResult.Success(response.data)
            }
        }
    }

}